import React, { useState, useCallback } from 'react';
import {
    Button,
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    Typography,
    Box,
    CircularProgress,
    IconButton,
    Alert,
    Stepper,
    Step,
    StepLabel
} from '@mui/material';
import {
    ImportExport,
    Close,
    CheckCircle,
    Error as ErrorIcon
} from '@mui/icons-material';
import { useFileSync } from '../../hooks/fileSystem/index.ts';
import { useNovel } from '../../context/NovelContext.tsx';

/**
 * 导入按钮组件属性
 */
interface ImportButtonProps {
    variant?: 'text' | 'outlined' | 'contained';
    size?: 'small' | 'medium' | 'large';
    onImportComplete?: (result: any) => void;
}

/**
 * 导入按钮组件
 * 提供从文件系统导入小说结构的功能，并展示导入进度
 */
const ImportButton: React.FC<ImportButtonProps> = ({
    variant = 'outlined',
    size = 'medium',
    onImportComplete
}) => {
    const [dialogOpen, setDialogOpen] = useState(false);
    const [importProgress, setImportProgress] = useState<{
        step: number;
        status: 'idle' | 'loading' | 'success' | 'error';
        message?: string;
        error?: string;
        result?: any;
    }>({
        step: 0,
        status: 'idle'
    });

    const { syncState, selectRootFolder, scanFolder, importNovelStructure } = useFileSync();
    const { importFromFileSystem } = useNovel();

    // 打开导入对话框
    const handleOpenDialog = useCallback(() => {
        setDialogOpen(true);
        setImportProgress({
            step: 0,
            status: 'idle'
        });
    }, []);

    // 关闭对话框
    const handleCloseDialog = useCallback(() => {
        setDialogOpen(false);
    }, []);

    // 开始导入流程
    const handleStartImport = useCallback(async () => {
        // 重置进度
        setImportProgress({
            step: 0,
            status: 'loading',
            message: '选择文件夹...'
        });

        try {
            // 步骤1: 选择根文件夹
            const folderResult = await selectRootFolder();
            if (!folderResult || !folderResult.folder) {
                setImportProgress({
                    step: 0,
                    status: 'error',
                    error: '未选择文件夹'
                });
                return;
            }

            setImportProgress({
                step: 1,
                status: 'loading',
                message: '扫描文件夹...'
            });

            // 步骤2: 扫描文件夹
            const scanResult = await scanFolder(folderResult.folder);

            setImportProgress({
                step: 2,
                status: 'loading',
                message: '转换为小说结构...'
            });

            // 步骤3: 转换为小说结构
            const novelStructure = await importNovelStructure();

            setImportProgress({
                step: 3,
                status: 'loading',
                message: '导入到系统...'
            });

            // 步骤4: 导入到系统
            const importResult = await importFromFileSystem();

            // 完成
            setImportProgress({
                step: 4,
                status: 'success',
                message: '导入完成',
                result: importResult
            });

            // 回调
            if (onImportComplete) {
                onImportComplete(importResult);
            }
        } catch (error: any) {
            console.error('导入失败:', error);
            setImportProgress({
                step: importProgress.step,
                status: 'error',
                error: error.message || '导入过程中发生错误'
            });
        }
    }, [selectRootFolder, scanFolder, importNovelStructure, importFromFileSystem, onImportComplete, importProgress.step]);

    // 导入步骤定义
    const steps = [
        '选择文件夹',
        '扫描文件结构',
        '转换小说结构',
        '导入系统',
        '完成'
    ];

    return (
        <>
            <Button
                variant={variant}
                size={size}
                startIcon={<ImportExport />}
                onClick={handleOpenDialog}
                color="primary"
            >
                导入
            </Button>

            <Dialog
                open={dialogOpen}
                onClose={handleCloseDialog}
                maxWidth="sm"
                fullWidth
            >
                <DialogTitle>
                    从文件夹导入小说
                    <IconButton
                        aria-label="close"
                        onClick={handleCloseDialog}
                        sx={{ position: 'absolute', right: 8, top: 8 }}
                    >
                        <Close />
                    </IconButton>
                </DialogTitle>

                <DialogContent>
                    <Typography variant="body2" gutterBottom>
                        此工具将扫描选择的文件夹，并根据文件结构导入小说内容。
                    </Typography>

                    {/* 导入进度步骤 */}
                    <Stepper activeStep={importProgress.step} sx={{ mt: 2, mb: 3 }}>
                        {steps.map((label, index) => (
                            <Step key={label} completed={importProgress.step > index}>
                                <StepLabel>{label}</StepLabel>
                            </Step>
                        ))}
                    </Stepper>

                    {/* 状态显示 */}
                    <Box sx={{ mt: 2, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', minHeight: '100px' }}>
                        {importProgress.status === 'idle' && (
                            <Typography>
                                点击"开始导入"按钮开始导入流程
                            </Typography>
                        )}

                        {importProgress.status === 'loading' && (
                            <>
                                <CircularProgress size={40} sx={{ mb: 2 }} />
                                <Typography>
                                    {importProgress.message || '正在处理...'}
                                </Typography>
                            </>
                        )}

                        {importProgress.status === 'error' && (
                            <>
                                <ErrorIcon color="error" fontSize="large" sx={{ mb: 2 }} />
                                <Alert severity="error" sx={{ width: '100%' }}>
                                    {importProgress.error || '导入失败'}
                                </Alert>
                            </>
                        )}

                        {importProgress.status === 'success' && (
                            <>
                                <CheckCircle color="success" fontSize="large" sx={{ mb: 2 }} />
                                <Typography color="success.main" gutterBottom>
                                    导入成功
                                </Typography>
                                {importProgress.result && (
                                    <Typography variant="body2">
                                        已导入小说: {importProgress.result.name || '未命名小说'}
                                    </Typography>
                                )}
                            </>
                        )}
                    </Box>
                </DialogContent>

                <DialogActions>
                    {importProgress.status === 'idle' && (
                        <>
                            <Button onClick={handleCloseDialog} color="inherit">
                                取消
                            </Button>
                            <Button
                                onClick={handleStartImport}
                                variant="contained"
                                color="primary"
                                startIcon={<ImportExport />}
                            >
                                开始导入
                            </Button>
                        </>
                    )}

                    {(importProgress.status === 'error' || importProgress.status === 'loading') && (
                        <>
                            <Button onClick={handleCloseDialog} color="inherit">
                                取消
                            </Button>
                            {importProgress.status === 'error' && (
                                <Button
                                    onClick={handleStartImport}
                                    variant="contained"
                                    color="primary"
                                >
                                    重试
                                </Button>
                            )}
                        </>
                    )}

                    {importProgress.status === 'success' && (
                        <Button onClick={handleCloseDialog} color="primary" variant="contained">
                            完成
                        </Button>
                    )}
                </DialogActions>
            </Dialog>
        </>
    );
};

export default ImportButton; 